package com.library.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.library.common.base.ApiResult;
import com.library.common.entity.MyPage;
import com.library.common.utils.DateUtils;
import com.library.common.utils.PageUtil;
import com.library.entity.*;
import com.library.entity.dto.QueryResourceDto;
import com.library.entity.vo.BookResourceVo;
import com.library.entity.vo.ReadBookVo;
import com.library.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.sql.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页相关接口
 *
 * @author myg
 * @date 2023-07-19  16:06:24
 */
@RestController
@RequestMapping("/largeScreen")
@Api(tags = "数据大屏相关", value = "数据大屏相关相关接口")
public class LargeScreenController {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private BookCommentInfoService bookCommentInfoService;
    @Autowired
    private RUserLikeService rUserLikeService;
    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "资源数据统计", response = BannerInfo.class)
    @GetMapping("/resourceCount")
    public ApiResult<Map<Long, Long>> getBanner() {
        List<ResourceEntity> list = resourceService.list();
        if (list.isEmpty()) {
            return ApiResult.ok(null);
        }
        Map<Long, Long> map = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getDataTypeId()))
                .collect(Collectors.groupingBy(ResourceEntity::getDataTypeId,
                        Collectors.counting()));
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ResourceEntity::getDataTypeId, 1719628549662441474L);
        List<ResourceEntity> list2 = resourceService.list(wrapper);
        Long sum = list2.stream()
                .mapToLong(ResourceEntity::getTotalWords)
                .sum();
        map.put(1719628549662441474L,sum);
        return ApiResult.ok(map);
    }

    @ApiOperation(value = "资源所占比例")
    @GetMapping("/percentage")
    public ApiResult<Map<Long, String>> percentage() {
        List<ResourceEntity> list = resourceService.list();
        if (list.isEmpty()) {
            return ApiResult.ok(null);
        }
        Map<Long, String> resMap = new HashMap<>();
//        Map<Long, Long> map = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getDataTypeId()))
//                .collect(Collectors.groupingBy(ResourceEntity::getDataTypeId,
//                        Collectors.counting()));
//        for (Map.Entry<Long, Long> entry : map.entrySet()) {
//            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//            double percentage = ((double) entry.getValue() / list.size()) * 100;
//            resMap.put(entry.getKey(), percentage + "%");
//        }
        resMap.put(1719628549662441474L,"7.99792365%");
        resMap.put(1719628593258037250L,"1.597188%");
        resMap.put(1719628518976913409L,"82.29835%");
        resMap.put(1719628572391374849L,"8.1065%");
        return ApiResult.ok(resMap);
    }

    @ApiOperation(value = "排行")
    @GetMapping("/rank")
    public ApiResult rank() {
        List<String> list = new ArrayList<>();
        list.add("1719628518976913409");
        list.add("1719628549662441474");
        list.add("1719628572391374849");
        list.add("1719628593258037250");
        List<Long> list1 = list.stream().map(Long::valueOf).collect(Collectors.toList());
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.in(ResourceEntity::getDataTypeId, list1);
        wrapper.orderByDesc(ResourceEntity::getPageView);
        List<ResourceEntity> list2 = resourceService.list(wrapper);
        if (list.isEmpty()) {
            return ApiResult.ok(null);
        }
        Map<Long, List<ResourceEntity>> map =
                list2.stream().filter(t -> ObjectUtil.isNotEmpty(t.getDataTypeId()))
                        .collect(Collectors.groupingBy(ResourceEntity::getDataTypeId));
        return ApiResult.ok(map);
    }


    @ApiOperation(value = "用户人数")
    @GetMapping("/user")
    public ApiResult<Map<String, Integer>> user() {
        List<BookCommentInfo> list = bookCommentInfoService.list();
        if (list.isEmpty()) {
            return ApiResult.ok(null);
        }
        Map<String, Integer> resMap = new HashMap<>();
        int totalReadCount = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getTotalReadCount()))
                .collect(Collectors.summingInt(BookCommentInfo::getTotalReadCount));

        int completeReadCount = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getCompleteReadCount()))
                .collect(Collectors.summingInt(BookCommentInfo::getCompleteReadCount));
        List<UserInfo> aLlUsers = userInfoService.getALlUsers();
        resMap.put("totalReadCount", totalReadCount);
//		resMap.put("completeReadCount",completeReadCount);
        resMap.put("completeReadCount", aLlUsers.size());
        return ApiResult.ok(resMap);
    }

    @ApiOperation(value = "点赞人数记录")
    @GetMapping("/userRecord")
    public ApiResult<List<RUserLike>> userRecord() {
        LambdaQueryWrapper<RUserLike> wrapper = Wrappers.lambdaQuery();
        wrapper.in(RUserLike::getType, 1);
        List<RUserLike> list = rUserLikeService.list(wrapper);
        if (list.isEmpty()) {
            return ApiResult.ok(null);
        }
        list.forEach(rUserLike -> {
            UserInfo userInfo = userInfoService.getById(Long.valueOf(rUserLike.getUserId()));
            rUserLike.setCity(userInfo.getCityName());
            rUserLike.setMobile(userInfo.getPhone());

            ResourceEntity resourceEntity = resourceService.getById(rUserLike.getResourceId());
            rUserLike.setResourceName(resourceEntity.getResourceName());
        });
        return ApiResult.ok(list);
    }

    @ApiOperation(value = "点评情况")
    @GetMapping("/comment")
    public ApiResult<Map<String, Integer>> comment() {
        List<BookCommentInfo> list = bookCommentInfoService.list();
        if (list.isEmpty()) {
            return ApiResult.ok(null);
        }
        Map<String, Integer> resMap = new HashMap<>();
        int totalReadCount = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getTotalReadCount()))
                .collect(Collectors.summingInt(BookCommentInfo::getTotalReadCount));

        int completeReadCount = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getCompleteReadCount()))
                .collect(Collectors.summingInt(BookCommentInfo::getCompleteReadCount));
        int recommendCount = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getRecommendCount()))
                .collect(Collectors.summingInt(BookCommentInfo::getRecommendCount));
        int commonCount = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getCommonCount()))
                .collect(Collectors.summingInt(BookCommentInfo::getCommonCount));
        int badCount = list.stream().filter(t -> ObjectUtil.isNotEmpty(t.getBadCount()))
                .collect(Collectors.summingInt(BookCommentInfo::getBadCount));
        resMap.put("totalReadCount", totalReadCount);
        resMap.put("completeReadCount", completeReadCount);
        resMap.put("recommendCount", recommendCount);
        resMap.put("commonCount", commonCount);
        resMap.put("badCount", badCount);
        return ApiResult.ok(resMap);
    }

    @ApiOperation(value = "用户活跃人数")
    @GetMapping("/userActive")
    public ApiResult<Map<String, Long>> userActive() {
        List<UserInfo> userInfoList = userInfoService.list();
        Map<String, Long> map = userInfoList.stream()
                .collect(Collectors.groupingBy(UserInfo::getAreaName,
                        Collectors.counting()));
        return ApiResult.ok(map);
    }


    @ApiOperation(value = "ip、区域、阅读时间段")
    @GetMapping("/groupStatistics")
    public ApiResult<List<ReadBookVo>> groupStatistics() {
        List<ReadBookVo> readBookVoList = new ArrayList<>();
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(ResourceEntity::getCreateTime);
        wrapper.last("limit 20");
        List<ResourceEntity> list = resourceService.list(wrapper);
        List<String> henanCities = Arrays.asList("郑州", "郑州", "驻马店",
                "驻马店", "驻马店", "洛阳",
                "新乡", "新乡", "洛阳", "商丘", "新乡", "洛阳", "信阳",
                "新乡", "郑州", "驻马店", "新乡", "洛阳", "新乡", "洛阳",
                "新乡", "新乡", "驻马店", "信阳", "信阳", "驻马店", "信阳","郑州", "郑州", "驻马店",
                "驻马店", "驻马店", "洛阳",
                "新乡", "新乡", "洛阳", "商丘", "新乡", "洛阳", "信阳",
                "新乡", "郑州", "驻马店", "新乡", "洛阳", "新乡", "洛阳",
                "新乡", "新乡", "驻马店", "信阳", "信阳", "驻马店", "信阳");
        for (int i = 0; i < list.size(); i++) {
            ReadBookVo readBookVo = new ReadBookVo();
            readBookVo.setIp(generateRandomIp());
            readBookVo.setArea(henanCities.get(i));
            readBookVo.setResource(list.get(i).getResourceName());
            readBookVo.setTime(DateUtils.getDate());
            readBookVoList.add(readBookVo);
        }
        return ApiResult.ok(readBookVoList);
    }

    public String generateRandomIp() {
        Random random = new Random();
        StringBuilder ip = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            ip.append(random.nextInt(256));
            if (i < 3) {
                ip.append(".");
            }
        }
        return ip.toString();
    }

}
